package com.newland.nxsms.cmpp;

import java.util.Vector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.newland.nxsms.NxSmsMain;

public final class CMPPTaskPool
{
	private static final Logger logger = LoggerFactory.getLogger(CMPPTaskPool.class);
	
	private  Vector<CMPPTaskInfo> infoBox = new Vector<CMPPTaskInfo>(1, 1);
	
	private long begainTime = 0L;
	
	private long endTime = 0L;
	
	private int sms_count = 0;
	
	private  Object synchObject = new Object();
	
	private CMPPTaskPool()
	{
		begainTime = System.currentTimeMillis();
	}
	
	private static class SingletonHolder
	{
		private static final CMPPTaskPool instance = new CMPPTaskPool();
	}

	public static CMPPTaskPool getInstance()
	{
		return SingletonHolder.instance;
	}
	
	public boolean pushTask(CMPPTaskInfo taskInfo)
	{
//		logger.info("add taskInfo "+taskInfo.getBase_id());
//		logger.info("vector size  "+infoBox.size());
		if (infoBox.add(taskInfo))
		{
			synchronized (synchObject)
			{
				synchObject.notify();
			}
			return true;
		}
		return false;
	}

	public synchronized CMPPTaskInfo popTask()
	{
		CMPPTaskInfo taskInfo = null;
		endTime = System.currentTimeMillis();
		if((endTime - begainTime) < 1000 && sms_count < 400) {
			try
			{
				if (infoBox.isEmpty() || infoBox.size() <= 0)
				{
					NxSmsMain.vectorIsOver = true;
					return null;
				}
				taskInfo = infoBox.get(0);
				infoBox.removeElementAt(0);
				sms_count ++ ;
//				logger.info("get seqId:{} task success, now queue size {}.", taskInfo.getSeqId(), infoBox.size());
			}
			catch (Exception e)
			{
				logger.error("get task failed", e);
				taskInfo = null;
			}
		} else {
			begainTime = endTime;
			sms_count = 0;
		}	
		return taskInfo;
	}

	public Integer getTasks()
	{
		return this.infoBox.size();
	}
}
